<?php

class RL_Principal_Storage_Store extends RL_Principal_Storage
/**

	Хранилище профилей принципала, основанная на хранилище объектов Store.

	PrincipalStorage_Store( &$principal )
			- $principal       -- к какому принципалу прикрепляться

	-------------------

	Суть структуры:
		* каждый профиль -- объект типа fuser

================================================================== v.1 (sibiryakov@gmail.com)
 */
{

	public function __construct( RL_Principal $principal )
	{
		parent::__construct( $principal );
		$this->store = &$this->rh->ctx->store;
	}

	public function loadById($id)
	{
		//$ql = 'select objects where user.oid == :oid and type == :type';
		//$rs = $this->store->find($ql, array('oid'=>$id, 'type'=>'fuser'));
		$db     = $this->store->db;
		$T      = $db->db_prefix;
		$id_sql = $db->quote($id);
		$sql = "SELECT U.*
			FROM {$T}objects U
			INNER JOIN {$T}class_user CU ON U.oid = CU.oid AND U.type = 'fuser'
			WHERE CU.oid = {$id_sql}
			LIMIT 1
		";
		$rs = $this->store->findSQL($sql);

		if ($rs && ($user = $rs->next())) {
			$res = $user->data;
			$res['user_id'] =$user->id;
		}

		return $res;
	}
	public function loadByDigest($digest)
	{
		$res = false;

		//$ql = 'select objects where auth_digest.digest == :digest and type == :type';
		do {
			// найдем сессию, связанную с дайджестом
			$db         = $this->store->db;
			$T          = $db->db_prefix;
			$digest_sql = $db->quote($digest);
			$sql = "SELECT O.*, AD.oid AS auth_digest_oid
				FROM {$T}objects O
				INNER JOIN {$T}class_auth_digest AD ON O.oid = AD.oid AND O.type = 'fsession'
				WHERE AD.digest = {$digest_sql} 
					AND AD.type = 0
				LIMIT 1
			";
			$rs = $this->store->findSQL($sql);
			if (!$rs || !($session = $rs->next())) { 
				error(__METHOD__." unknown session digest '$digest'");
				break; 
			} 

			// ищем пользователя этой сессии
			$session_oid   = $session->id;
			$session_mtime = $session->mtime;
			$user_oid = $session->data['user_oid'];
			if (!$user_oid) {
				error(__METHOD__." unknown user in the session '{$digest}'");
				break; 
			} 
			$sql = "SELECT O.*
							FROM {$T}objects O
							WHERE O.oid = {$user_oid} 
							LIMIT 1
			";
			$rs = $this->store->findSQL($sql);
			if (!$rs || !($user = $rs->next())) {
				error(__METHOD__." can't find user '{$user_oid}' for session '{$digest}'");
				break; 
			}

			$res = $user->data;
			$res['user_id'] =$user->id;

			// обновим активность сессии, если нужно.
			if (time() - strtotime($session_mtime) > 60*60*24) {
				$sql = "UPDATE {$T}objects SET mtime = NOW() WHERE oid = '$session_oid'";
				$this->store->db->lowlevel->execute($sql);
			}
		} while (false);

		return $res;
	}
	public function loadByLogin($login, $realm = NULL)
	{
		$res = false;

		//$ql = 'select objects where user.login == :login and type == :type';
		//if (isset($realm)) { $ql .= ' and user.realm = :ream'; }
		//$rs = $this->store->find( $ql, array('login'=>$login, 'type'=>'fuser', 'realm' => $realm) );

		$db        = $this->store->db;
		$T         = $db->db_prefix;
		$login_sql = $db->quote($login);
		$sql = "SELECT U.*
			FROM {$T}objects U
			INNER JOIN {$T}class_user CU ON U.oid = CU.oid AND U.type = 'fuser'
			WHERE CU.login = {$login_sql} 
			LIMIT 1
		";

		$rs = $this->store->findSQL($sql);

		if ($rs && ($user = $rs->next())) {
			$res = $user->data;
			$res['user_id'] =$user->id;
		}

		return $res;
	}

	public function setStoredPassword( $user_data, $new_invariant )
	{
	  $login = $user_data["login"];
		$realm = $user_data["realm"];
		$db_table = 'store_class_user';
		$sql = "update ".$db_table
					 ." set password = ".$this->rh->ctx->db->Quote($new_invariant)
					 ." where "
					 ."     login=".$this->rh->ctx->db->Quote($login)
					 //." and realm=".$this->rh->ctx->db->Quote($realm)
					 ;
		$this->rh->ctx->db->Query( $sql );
		return true;
	}
	public function setStoredDigest ($user_data, $digest)
	{
		$store = $this->store;

		trace(var_export($user_data, true));
		if (isset($user_data["user_id"]) && ($user_oid = $user_data["user_id"])) {
			$store->db->begin();
			$sd = array(
				'user_oid' => $user_oid,
				'digest' => $digest,
				'type' => 0,
			);
			$session = $store->create('fsession', $sd);
			$session->save();
			$store->addProperty($session->id, 'auth_digest', array(
				'user_oid' => $user_oid, 
				  'digest' => $digest, 
				    'type' => 0,
				)
			);
			$store->db->end();
		}
		return $user_data;
	}

	protected function _setLoginDatetime( $user_data, $datetime )
	{
	/*
		 $login = $user_data["login"];
		 $realm = $user_data["realm"];
		 $dt = date("Y-m-d H:i:s", $datetime );
		 $sql = "update ".$this->db_table.
						" set login_datetime = ".$this->rh->ctx->db->Quote($dt).
						" where ".
						"     login=".$this->rh->ctx->db->Quote($login).
						" and realm=".$this->rh->ctx->db->Quote($realm);
		 $this->rh->ctx->db->Query( $sql );
	 */
		return true;
	}


	// EOC{ PrincipalStorage_db }
}


?>
